package cn.bdqn.witcity.service;

import cn.bdqn.witcity.entity.Bar;
import cn.bdqn.witcity.entity.Menu;
import cn.bdqn.witcity.entity.vo.MenuVo;
import cn.bdqn.witcity.mapper.MenuMapper;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class MenuServiceImpl implements MenuService{
    @Resource
    MenuMapper menuMapper;
    @Override
    public List<Menu> getAllChildMenu(Integer parentId) {
        return menuMapper.getAllChildMenu(parentId);
    }

    @Override
    public List<Bar> garAllParentMenuByRole() {
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        List<Menu> menus=new ArrayList<>();
        List<Bar> bars=new ArrayList<>();
        if(!(authentication instanceof AnonymousAuthenticationToken)){
            Object[] roles=authentication.getAuthorities().toArray();
            for(Object role:roles){
                List<Menu> menus1=menuMapper.getMenuByRole(role.toString());
                menus.addAll(menus1);
            }
            Set<Menu> userSet=new HashSet<>(menus);
            List<Menu> menuDistinct=new ArrayList<>(userSet);
            for(int i=0;i<menuDistinct.size();i++){
                Menu menu=menuDistinct.get(i);
                Bar bar=new Bar();
                bar.setId(menu.getId());
                bar.setName(menu.getName());
                bar.setUrl(menu.getUrl());
                List<Menu> menus2=this.getAllChildMenu(menu.getId());
                bar.setMenus(menus2);
                bars.add(bar);
            }
        }
        return bars;
    }

    @Override
    public List<Menu> getAllMenu() {
        return menuMapper.getAllMenu();
    }

    @Override
    public List<Menu> getAllMenuByPage(MenuVo menuVo) {
        return menuMapper.getAllMenuByPage(menuVo);
    }

    @Override
    public int getMenuCount(MenuVo menuVo) {
        return menuMapper.getMenuCount(menuVo);
    }

    @Override
    public List<Menu> getAllParentMenu() {
        return menuMapper.getAllParentMenu();
    }
}
